cc.Class({
    extends: cc.Component,

    properties: {
        brickPrefab: cc.Prefab,             // 砖块预制
        bricksLayout: cc.Node,              // 砖块布局
        bar: cc.Node,                       // 条形板
        ball: cc.Node                       // 小球
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        cc.director.getPhysicsManager().enabled = true;                 // 开启物理引擎

        this.ball.getComponent('Ball').init(this);                      // 将this传到Ball.js中

        // 首先获取当前关卡信息
        let currentLevelInfo = JSON.parse(cc.sys.localStorage.getItem('currentLevelInfo'));
        this.level = currentLevelInfo['level'];                                           // 第几关
        this.row = currentLevelInfo['row'];                                               // 行数
        this.col = currentLevelInfo['col'];                                               // 列数
        this.spaceX = currentLevelInfo['spaceX'];                                         // 列间隔
        this.spaceY = currentLevelInfo['spaceY'];                                         // 行间隔
        this.brickWidth = currentLevelInfo['brickWidth'];                                 // 砖块宽度
        this.brickHeight = currentLevelInfo['brickHeight'];                               // 砖块高度
        this.transparentBricks = currentLevelInfo['transparentBricks'];                   // 刚开始就透明的砖块
        this.speed = 20;                                                                  // bar移动速度

        this.bricksArray = [];                                                            // 砖块数组

        this.initBricksLayout();                                                          // 初始化砖块布局

        // 初始化键盘输入监听
        this.moveDir = null;                                                              // 用于确定左右移动方向
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this); 
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);  
    },

    initBricksLayout () {
        // 设置bricksLayout相关属性
        this.bricksLayout.getComponent(cc.Layout).spacingX = this.spaceX;
        this.bricksLayout.getComponent(cc.Layout).spacingY = this.spaceY;
        this.bricksLayout.getComponent(cc.Layout).cellSize.width = this.brickWidth;
        this.bricksLayout.getComponent(cc.Layout).cellSize.height = this.brickHeight;
        this.bricksLayout.width = this.col*this.brickWidth + (this.col-1)*this.spaceX;
        this.bricksLayout.height = this.row*this.brickHeight + (this.row-1)*this.spaceY;

        // 循环放置砖块
        for (let i=0; i<this.row; i++) {
            for (let j=0; j<this.col; j++) {

                let brick = cc.instantiate(this.brickPrefab);
                brick.x = 99999;      // 为了跟bricksLayout节点区分，好同步到物理引擎

                // 设置砖块的碰撞规定尺寸
                brick.getComponent(cc.PhysicsBoxCollider).width = this.brickWidth;
                brick.getComponent(cc.PhysicsBoxCollider).height = this.brickHeight;

                // 将砖块添加到数组和布局中
                this.bricksArray.push(brick);
                this.bricksLayout.addChild(brick);

                // 看看是不是透明砖块
                for (let k=0; k<this.transparentBricks.length; k++) {
                    if (this.transparentBricks[k][0]==i && this.transparentBricks[k][1]==j) {
                        brick.opacity = 0;                             // 变透明
                        brick.removeComponent(cc.RigidBody);           // 移出刚体组件，让该砖块无法与球碰撞
                    }
                }
            }
        }
    },

    onKeyDown (event) {
        // 控制bar左右移动
        switch(event.keyCode) {
            case cc.macro.KEY.a:
            case cc.macro.KEY.left:
                this.moveDir = 'left';
                break;
            
            case cc.macro.KEY.d:
            case cc.macro.KEY.right:
                this.moveDir = 'right';
                break;
        }
    },

    onKeyUp (event) {
        this.moveDir = '';
    },

    win () {
        // 更新关卡信息
        let settings = JSON.parse(cc.sys.localStorage.getItem('settings'));
        settings[this.level-1]['levelState'] = 'PASSED';        // 当前关卡状态变为通过(数组下标-1)
        settings[this.level]['levelState'] = 'UNLOCKED';        // 下一关卡状态变为解锁
        cc.sys.localStorage.setItem('settings', JSON.stringify(settings));

        console.log('恭喜过关！');
        cc.director.loadScene('关卡');
    },

    lose () {
        console.log('输了= =');
        cc.director.loadScene('打砖块');
    },

    update (dt) {
        // 移动bar
        if (this.moveDir == 'left') {
            this.bar.x -= this.speed;
        }
        else if (this.moveDir == 'right') {
            this.bar.x += this.speed;
        }

        // 限制bar
        let canvasWidth = cc.Canvas.instance.node.width;
        let canvasHeight = cc.Canvas.instance.node.height;

        if (this.bar.x < -canvasWidth/2+this.bar.width/2) {
            this.bar.x = -canvasWidth/2+this.bar.width/2;
        }
        
        if (this.bar.x > canvasWidth/2-this.bar.width/2) {
            this.bar.x = canvasWidth/2-this.bar.width/2;
        }

        // 根据小球位置来判断输赢
        if (this.ball.y < -canvasHeight/2) {
            this.lose();
        }
    },
});
